import axios from 'axios'
import qs from 'qs';
import _ from 'lodash';
// import { Loading } from 'element-ui';


import {
    Message, MessageBox
} from 'element-ui'
import store from '@/store'

const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    // timeout: 10000, // request timeout
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        'Authorization': `Bearer ${store.state.token}`
    },
    // params: {
    //     token: store.state.token
    // },
    // `transformRequest` 允许在向服务器发送前，修改请求数据
    // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
    transformRequest: [
        function (data) {
            // return qs.stringify(data);
            // console.log(data,'??????')
            return qs.stringify(data)
        }
    ],
    // `transformResponse` 在传递给 then/catch 前，允许修改响应数据
    transformResponse: [function (data) {
        // !!! 关闭 loading !!!
        return data
    }],
    paramsSerializer(data) {
        return qs.stringify(data);
    }
})

// request interceptor
service.interceptors.request.use(config => {
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
    response => {
        response.data = _.isString(response.data) ? JSON.parse(response.data) : response.data;
        // console.log(response.data.code)
        if (response.data.code == 200||response.data.code == 201) {
            return response.data
        } else {
            Message({
                message: response.data.msg || response.data.message,
                type: 'error'
            })
            return Promise.reject(response.data)
        }
    },
    error => {
        // !!! 关闭 loading !!!
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    })

export default service